package com.datastructure.test.printmatrixclockwise;

import java.util.ArrayList;

public class PrintMatrixClockwise {

    public static void main(String[] args) {
        PrintMatrixClockwise printMatrixClockwise = new PrintMatrixClockwise();
        int[][] matrix = {{3},{2}};
        ArrayList<Integer> integers = printMatrixClockwise.printMatrix(matrix);
        System.out.println(integers);
    }

    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> result = new ArrayList<>();
        if(matrix==null||matrix.length==0){
            return result;
        }
        int left = 0;
        int right = matrix[0].length-1;
        int top = 0;
        int bottom = matrix.length-1;
        while (left<(matrix[0].length+1)/2&&top<(matrix.length+1)/2){
            for(int i = left;i<=right;i++){
                result.add(matrix[top][i]);
            }
            for(int i =top+1;i<=bottom;i++){
                result.add(matrix[i][right]);
            }
            for(int i = right-1;i>=left&&(top!=bottom);i--){
                result.add(matrix[bottom-1][i]);
            }
            for(int i = bottom-1;i>=(top+1)&&(left!=right);i--){
                result.add(matrix[i][left]);
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        return result;
    }
}
